#!/bin/bash -Eu

PEAC_VERSION=0.20

# trap onexit 1 2 3 15 ERR

# function onexit() {
#     local exit_status=${1:-$?}
#     echo Exiting $0 with $exit_status
#     exit $exit_status
# }

function ShowHelp() {
  echo ""
  echo "./peac sw list"
  echo "./peac sw install VO_ALICE@ROOT::v5-28-08d"
  echo ""
}

if [ $# -lt 1 ];then
  ShowHelp
  return 1
fi

function CatFile() {
    cat $1 | grep -v "PEAC_VERSION" >> $2
    return 0
}

function InstallPackage() {
  local MY_VO=`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $1}'`
  local MY_NAME=`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $2}'`
  local MY_VER=`echo $1 | awk -F ':' '{print $3}'`
  local MY_INSTALL_DIR="$2"

  if [ -z "$MY_VO" -o -z "$MY_NAME" -o -z "$MY_VER" ];then
    echo "Wrong package format [$1] !!!"
    exit 1
  fi
  
  local MY_TEMPLATE_FILE="$PEAC_SW_TEMPLATE_DIR/$MY_VO@$MY_NAME.pbuild"
  if [ ! -f $MY_TEMPLATE_FILE ];then
    echo "Template $MY_TEMPLATE_FILE is not available !!!"
    return 1
  fi
  MY_PACKAGE_DIR="$1"
  MY_PACKAGE_DIR=${MY_PACKAGE_DIR/@/\/}
  MY_PACKAGE_DIR=${MY_PACKAGE_DIR/::/\/}
  PEAC_BUILD_TMP_DIR="$PEAC_SW_TMP_DIR/$MY_PACKAGE_DIR"

  rm -Rf $PEAC_BUILD_TMP_DIR
  mkdir -p $PEAC_BUILD_TMP_DIR

  local MY_BUILD_FILE=$PEAC_BUILD_TMP_DIR/$MY_VO@$MY_NAME::$MY_VER.pbuild

  echo "#!/bin/bash" > $MY_BUILD_FILE
  echo "" >> $MY_BUILD_FILE
 
  echo "PEAC_BUILD_TMP_DIR=\"$PEAC_BUILD_TMP_DIR\"" >> $MY_BUILD_FILE
  echo "PEAC_PACKAGE_VO=\"$MY_VO\"" >> $MY_BUILD_FILE
  echo "PEAC_PACKAGE_NAME=\"$MY_NAME\"" >> $MY_BUILD_FILE
  echo "PEAC_PACKAGE_VERSION=\"$MY_VER\"">> $MY_BUILD_FILE
  echo "PEAC_PACKAGE_INSTALL_DIR=\"$2\"" >> $MY_BUILD_FILE
  echo "PEAC_PACKAGE_SVN_REV=\"\"" >> $MY_BUILD_FILE
  echo "PEAC_PACKAGE_SVN_REV_FORCE=\"0\"" >> $MY_BUILD_FILE

  # set init return Value
  export PEAC_RET="0"

  
  if [ "$MY_VO@$MY_NAME" == "VO_PEAC@Xrootd" ];then
    echo "PEAC_SW_BUILD_FORCE=\"1\"" >> $MY_BUILD_FILE
  else
    echo "PEAC_SW_BUILD_FORCE=\"0\"" >> $MY_BUILD_FILE
  fi
  
  CatFile $PEAC_SYS_DIR/$PEAC_BUILD_CONF_FILE $MY_BUILD_FILE

  CatFile $MY_TEMPLATE_FILE $MY_BUILD_FILE

  # adding users template for specific version
  if [ -f $PEAC_SW_TEMPLATE_USER_DIR/$MY_VO@$MY_NAME::$MY_VER.pbuild ];then
    echo "Using user's $PEAC_SW_TEMPLATE_USER_DIR/$MY_VO@$MY_NAME::$MY_VER.pbuild [not working yet]..."
#     CatFile $PEAC_SW_TEMPLATE_USER_DIR/$MY_VO@$MY_NAME::$MY_VER.pbuild $MY_BUILD_FILE
  fi
  

  MY_FUNC="identify_system svn_info send_to_master check_local_binary check_binary lock download unpack make_clean configure make make_install generate_env_peac generate_env distribution install test"
  # add missing function ()
  for MYOPT in $MY_FUNC; do
    MY_FUNC=`grep -E "PEAC_$MYOPT" $MY_BUILD_FILE | grep -v '#' | grep -v "PEAC_${MYOPT}_"`
    if [ -z "$MY_FUNC" ];then
#       echo "CatFile $PEAC_SW_TEMPLATE_DIR/peac/peac-$MYOPT.pbuild $MY_BUILD_FILE"
      CatFile $PEAC_SW_TEMPLATE_DIR/peac/peac-$MYOPT.pbuild $MY_BUILD_FILE
    fi
  done

  CatFile $PEAC_SW_TEMPLATE_DIR/peac/peac-base.pbuild $MY_BUILD_FILE
  CatFile $PEAC_SW_TEMPLATE_DIR/peac/peac-run.pbuild $MY_BUILD_FILE

  MY_FUNC="install"
  # cleaning previous logs
  for MYOPT in $MY_FUNC; do
    rm -f $PEAC_BUILD_TMP_DIR/$MYOPT.out
  done
  
  # doing prcesses
  for MYOPT in $MY_FUNC; do
    . $MY_BUILD_FILE $MYOPT "$3" "$4"
    if [ "$PEAC_RET" == "0" ];then
      echo "==> Package $PEAC_PACKAGE_VO@$PEAC_PACKAGE_NAME::$PEAC_PACKAGE_VERSION installed [ OK ] at $PEAC_PACKAGE_INSTALL_DIR/$PEAC_PACKAGE_VO/$PEAC_PACKAGE_NAME/$PEAC_PACKAGE_VERSION"
      return 0
    elif [ "$PEAC_RET" == "10" ];then
      echo "==> Package $PEAC_PACKAGE_VO@$PEAC_PACKAGE_NAME::$PEAC_PACKAGE_VERSION installed [ SKIPPING ]"
      return 0
    else
      echo "==> Package $PEAC_PACKAGE_VO@$PEAC_PACKAGE_NAME::$PEAC_PACKAGE_VERSION installed [ FAILED ]"
      return 1
    fi
  done

}

function IdentifySystem() {
  cat $PEAC_SW_TEMPLATE_DIR/peac/peac-identify_system.pbuild > /tmp/$USER-peac-identify_system.pbuild
  echo "PEAC_identify_system " >> /tmp/$USER-peac-identify_system.pbuild
  echo "`. /tmp/$USER-peac-identify_system.pbuild`"
  rm /tmp/$USER-peac-identify_system.pbuild
}

function ShowPackages() {

  local MY_SYSTEM=$(IdentifySystem)

  local MY_PWD=`pwd`

  echo ""
  echo "Your system is $MY_SYSTEM"
  if [ ! -d $PEAC_SW_DIR/$MY_SYSTEM ];then
    echo ""
    echo "  No packages found !!!"
    echo ""
    return 1
  fi
  cd $PEAC_SW_DIR/$MY_SYSTEM


  for MY_PACKAGE in `find . -name peac-env.sh`;do
    MY_PACKAGE=${MY_PACKAGE/.\//}
    local MY_VO=`echo "$MY_PACKAGE" | awk -F '/' '{print $1}'`
    local MY_NAME=`echo "$MY_PACKAGE" | awk -F '/' '{print $2}'`
    local MY_VER=`echo "$MY_PACKAGE" | awk -F '/' '{print $3}'`
    echo "  $MY_VO@$MY_NAME::$MY_VER"
  done
  cd $MY_PWD
}

function RemovePackage() {
  local MY_VO=`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $1}'`
  local MY_NAME=`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $2}'`
  local MY_VER=`echo $1 | awk -F ':' '{print $3}'`
  if [ -d $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER ];then
    rm -Rf $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER
#     echo "$PEAC_SW_PACKAGE_DIR/$MY_VO@$MY_NAME::$MY_VER-$(IdentifySystem).tar.gz"
    rm -f $PEAC_SW_PACKAGE_DIR/$MY_VO@$MY_NAME::$MY_VER-$(IdentifySystem).tar.gz
    echo "Package $1 was removed from $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER"
  else
    echo "Error: Directory $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER doesn't exist !!!"
#     exit 1
  fi
}

function SourcePackage() {
  MY_PKG_LIST=$(GenerateListOfPackagesToBeInstalled $1)
#   echo "$MY_PKG_LIST"
  for PKG in $MY_PKG_LIST; do
#     echo "===> $PKG"
    local MY_VO=`echo $PKG | awk -F ':' '{print $1}' | awk -F '@' '{print $1}'`
    local MY_NAME=`echo $PKG | awk -F ':' '{print $1}' | awk -F '@' '{print $2}'`
    local MY_VER=`echo $PKG | awk -F ':' '{print $3}'`

#     echo "$PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER/peac-env.sh"

    if [ -f $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER/peac-env.sh ];then
      . $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER/peac-env.sh 
    fi

  done 
}

function CheckDepFile() {
  if [ ! -f $PEAC_SW_PACKAGE_DEP_DIR/$1 ];then
    wget -q -O $PEAC_SW_PACKAGE_DEP_DIR/$1.new http://peac.googlecode.com/svn/trunk/sw/dep/$1
    if [ "$?" != "0" ];then
      echo ""
      echo "Problem downloading http://peac.googlecode.com/svn/trunk/sw/dep/$1 !!!"
      echo "Reusing old one from $PEAC_SW_PACKAGE_DEP_DIR/$1"
    else
      mv $PEAC_SW_PACKAGE_DEP_DIR/$1.new $PEAC_SW_PACKAGE_DEP_DIR/$1
    fi
  fi
  if [ ! -f $PEAC_SW_PACKAGE_DEP_DIR/$1 ];then
    echo ""
    echo "File $PEAC_SW_PACKAGE_DEP_DIR/$1 was not found !!! Exiting ..."
    exit 1
  fi
}

function PackageInfo() {
  local MY_VO=`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $1}'`
  local MY_PACKAGE
  local MY_DEPS
  local MY_MESSAGE="No Package avialable"
  echo "file is $PEAC_SW_PACKAGE_DEP_DIR/$MY_VO.dep"

  while read line;do
    echo "$line"
    MY_PACKAGE=`echo $line | awk '{print $1}'`
    MY_DEPS=`echo $line | awk '{print $2}'`
    if [ "$MY_PACKAGE " == "$1 " ];then
      MY_MESSAGE=""
      echo "Dep for package $1 are : "
      MY_DEPS=${MY_DEPS//,/ }
      for DEP in $MY_DEPS;do
	echo "  $DEP"
      done
    fi
  done < $PEAC_SW_PACKAGE_DEP_DIR/$MY_VO.dep

  if [ -n "$MY_MESSAGE" ];then
    echo "  $MY_MESSAGE"
  fi
}

function GenerateListOfPackagesToBeInstalled() {

  PACKAGE_LIST="$1 $PACKAGE_LIST"
  if [ -z "$1" ];then
    echo "$PACKAGE_LIST"
    return 0
  fi

  local MY_VO=`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $1}'`
  local MY_VO=`echo $1 | awk -F ':' '{print $1}' | awk -F '@' '{print $1}'`
  local MY_PACKAGE
  local MY_DEPS

  while read line;do
    MY_PACKAGE=`echo $line | awk '{print $1}'`
    MY_DEPS=`echo $line | awk '{print $2}'`
    if [ "$MY_PACKAGE" == "$1" ];then
      MY_DEPS=${MY_DEPS/,/ }
      for MY_DEP in $MY_DEPS;do
        GenerateListOfPackagesToBeInstalled $MY_DEP DONTPRINT
      done
      break
    fi
  done < $PEAC_SW_PACKAGE_DEP_DIR/$MY_VO.dep

  if [ -z $2 ];then 
    echo "$PACKAGE_LIST"
  fi
}

function InstallPackageFull() {
  MY_PKG_LIST=$(GenerateListOfPackagesToBeInstalled $1)
#   echo "$MY_PKG_LIST" > /tmp/peac-packagelist
  MY_PKG_LIST=$( awk 'BEGIN{RS=ORS=" "}!a[$0]++' <<<$MY_PKG_LIST );
#   echo "$MY_PKG_LIST"
#   return 1
  PEAC_PACKAGE_DEP_CURRENT=""
  for PKG in $MY_PKG_LIST; do
#     echo "===> $PKG"
    local MY_VO=`echo $PKG | awk -F ':' '{print $1}' | awk -F '@' '{print $1}'`
    local MY_NAME=`echo $PKG | awk -F ':' '{print $1}' | awk -F '@' '{print $2}'`
    local MY_VER=`echo $PKG | awk -F ':' '{print $3}'`

    local MY_VER_REV=`echo $MY_VER | awk -F '_' '{print $NF}'`

#     echo "$PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER/peac-env.sh"

    if [ "$PKG" == "VO_PEAC@PoD::trunk" ];then
      POD_TRUNK_VER=`wget -q -O -  http://pod.gsi.de/download.html | grep "http://pod.gsi.de/releases/pod/nightly" | head -n 1 | awk -F= '{print $5}' | awk '{print $1}' | awk -F 'PoD-' '{print $2}' | awk -F '.tar.gz' '{print $1}'`
      MY_VER=$POD_TRUNK_VER
    fi


    if [ -f $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER/peac-env.sh ];then
      echo "  [$MY_VO@$MY_NAME::$MY_VER] [ OK ]"
      source $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER/peac-env.sh 
    else
      PKG=${PKG/_$MY_VER_REV}
      InstallPackage "$PKG" "$2" "$3" "$MY_VER_REV"
      if [ "$PEAC_RET" == "10" ];then
        return 0
      fi
      if [ -f $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER/peac-env.sh ];then
      
        source $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER/peac-env.sh
      else
        echo "Could not source $PEAC_SW_DIR/$(IdentifySystem)/$MY_VO/$MY_NAME/$MY_VER/peac-env.sh !!!!!!"
      fi
    fi
    PEAC_PACKAGE_DEP_CURRENT="$PKG"

  done 
}

function SyncSoftwareFromList() {
  if [ -z "$1" -a ! -f $1 ];then
    ShowHelp
  fi
  local MY_PACKAGES_TO_INSTALL=""
  echo "==> Doing sync from file $PEAC_SW_PACKAGE_DEP_DIR/$1.soft"
  while read line;do
    if [ ${line:0:1} != "#" ];then
      MY_PACKAGES_TO_INSTALL="$MY_PACKAGES_TO_INSTALL $line"
    fi
  done < $PEAC_SW_PACKAGE_DEP_DIR/$1.soft

  for MY_PKG in $MY_PACKAGES_TO_INSTALL;do
    InstallPackageFull $MY_PKG $PEAC_SW_DIR $2
  done
}

echo -n "Checking for updates "
# checking Dep file
CheckDepFile VO_PEAC.dep 
CheckDepFile VO_ALICE.dep
# CheckDepFile VO_ALICE.dep
echo "[ OK ]"

# echo "Installing $1 ..."
if [ "$1" == "install" ];then
  MY_INSTALL_ARGS="$3"
  if [ -z "$MY_INSTALL_ARGS" ];then
    MY_INSTALL_ARGS="normal"
  fi
  InstallPackageFull "$2" $PEAC_SW_DIR $MY_INSTALL_ARGS
elif [ "$1" == "sync" ];then
  SyncSoftwareFromList "$2"
elif [ "$1" == "info" ];then
  PackageInfo $2
elif [ "$1" == "system" ];then
  IdentifySystem
elif [ "$1" == "list" ];then
  ShowPackages
elif [ "$1" == "source" ];then
  SourcePackage $2
elif [ "$1" == "remove" ];then
  shift
#   echo "Packages will be removed $*"
  for MYPKG in $*;do
    echo "Removing $MYPKG ... "
    RemovePackage $MYPKG
  done
else
  ShowHelp
fi


# rm -Rf $PEAC_BUILD_TMP_DIR

# onexit
